<template>
  <page-panel-new class="buttons">
    <el-button
      class="commonBtn"
      @click="handleBack"
    >
      返回
    </el-button>
    <el-button
      v-if="!isView"
      type="primary"
      @click="visible = true;"
    >
      回复
    </el-button>
    <el-button
      v-if="!isView && canComplete"
      type="primary"
      @click="handleComplete()"
    >
      完成问题
    </el-button>
    <common-dialog
      v-if="visible"
      v-model="visible"
      v-drag
      width="70%"
      class="reply-dialog"
      label=""
      dialog-title="回复"
      :append-to-body="true"
      :destroy-on-close="true"
      @ok="handleReply"
    >
      <el-form
        ref="form"
        :inline="true"
        class="form-layout"
        :rules="rules"
        :model="replyModel"
      >
        <el-form-item
          label="问题描述:"
          class="form-layout__item-col1"
        >
          <page-panel-new style="height: 100%; margin: 5px 0 0;">
            <input-rich-form
              :content-key="contentKey"
              :get-model="getModel(model)"
              :need-token="true"
              :download-fn="downFile"
            />
          </page-panel-new>
        </el-form-item>
        <el-form-item
          label="新增回复:"
          prop="context"
          class="form-layout__item-col1"
        >
          <input-rich
            v-model="replyModel.context"
            :height="270"
            :upload-fn="uploadFn"
            :download-fn="downFile"
            :required="true"
            @img="handleImg"
          />
          <p>
            注: 请注意！回复内容应遵守相关法律法规和基本道德规范，不包含诽谤、歧视、侵权，违法等行为，并避免敏感话题和广告宣传，如发现违规内容，该问题的审核将无法通过。
          </p>
        </el-form-item>
        <el-form-item
          class="upload-item"
          label="回复附件:"
          prop="customName"
          label-width="110px"
        >
          <file-upload
            v-model="replyModel.orderAttachment"
            :limit="5"
            :is-show-tip="false"
            :drag="false"
            biz-path="approve/oo-csc-upp-approve-atom"
            upload-type="minio"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          class="commonBtn"
          @click="visible = false"
        >
          取消
        </el-button>
      </template>
    </common-dialog>
  </page-panel-new>
</template>

<script>
import returnPaterPage from "@/utils/returnPaterPage";
import CommonDialog from "@/components/mainEntrance/dialog/CommonDialog.vue";
import FileUpload from "@/components/mainEntrance/FileUpload/index.vue";
import InputRich from "@/components/inputRich/index.vue";
import InputRichForm from "@/components/inputRich/InputRichForm.vue";

import { useInputRichMixins } from "@/components/inputRich/mixins/useInputRichMixins.js";
import { checkCurrentReply, reply, complete } from "@/api/workOrder/allWorkOrders.js";
import { encode } from "@/utils/base64Convert.js";

export default {
  name: "HeaderButtons",
  components: {
    CommonDialog,
    FileUpload,
    InputRich,
    InputRichForm
  },
  mixins: [useInputRichMixins],
  props: {
    model: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      returnName: "AllWorkOrders",
      visible: false,
      rules: {
        context: [{ required: true, message: "请输入回复内容", trigger: ["blur", "change"] }]
      },
      replyModel: {
        orderAttachment: "",
        context: ""
      },
      contentKey: "loading"
    };
  },
  computed: {
    isView() {
      return this.$route.params.action === "View";
    },
    canComplete() {
      return this.model.canComplete;
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.replyModel = {
          orderAttachment: "",
          context: ""
        };
      }
    },
    model(val) {
      if (val) {
        this.contentKey = Date.now().toString();
      }
    }
  },
  methods: {
    handleBack() {
      returnPaterPage(this.$route.path, this.returnName);
    },
    handleReply() {
      this.$refs.form.validate(valid => {
        if (valid) {
          checkCurrentReply({
            dataVersion: this.model.dataVersion,
            orderId: this.model.orderId
          }).then(res => {
            if (res?.data?.data) {
              this.$confirm("有新的回复消息, 是否继续回复?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(() => {
                this.handleReplyData();
              }).catch(() => {
                this.visible = false;
                this.$emit("load");
              });
            } else {
              this.handleReplyData();
            }
          });
        }
      });
    },
    handleReplyData() {
      this.replyModel.orderContext = this.replyModel.context;
      if (Object.keys(this.imgUrls).length) {
        Object.keys(this.imgUrls).forEach(key => {
          this.replyModel.orderContext = this.replyModel.orderContext.replace(key, this.imgUrls[key]);
        });
      }
      this.replyModel.orderContext = encode(this.replyModel.orderContext);
      const { orderId, dataVersion } = this.model;
      reply({ ...this.replyModel, orderId, dataVersion }).then(() => {
        this.$message.success("回复成功！");
        this.handleBack();
      });
    },
    handleComplete() {
      this.$confirm("确认完成该问题吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        complete(this.model.orderId).then(() => {
          this.$message.success("确认成功！");
          this.handleBack();
        });
      });
    },
    getModel(model) {
      const item = model?.replyList?.[0]?.orderContext;
      return () => Promise.resolve({
        "content": item ? decodeURI(item) : "",
        "cssContent": "img { max-width: 450px; object-fit: contain; }"
      });
    }
  }
};
</script>

<style lang="less" scoped>
@import "@/assets/styles/less/form.less";

.form-layout {
  overflow-y: auto;
  max-height: 70vh;

  .form-layout(100px);

  /deep/ .upload-file-text {
    display: inline-block;
  }
}

.buttons {
  margin-top: 0;
  margin-bottom: 20px;
  height: 60px !important;

  /deep/ .g-w100 {
    padding: 10px !important;
  }

  .reply-dialog {
    display: inline-block;
    margin: 0 10px;
  }
}
</style>